package com.dubito.lucene;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import java.io.*;

/**
 * 创建索引库
 *
 * @author liliang
 * @description:
 * @date 2018/4/28.
 */
public class CreateIndex {

    public static void main(String[] args) throws Exception {
        //创建索引库存储目录
        FSDirectory directory = FSDirectory.open(new File("/Users/liliang/Downloads/index_db"));
        // 创建分词器 (单字分词器)
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
        // 创建 indexConfig
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_40, analyzer);
        // 设置打开索引库的模式
        indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
        // 创建IndexWriter(索引库存储目录,配置信息)
        IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);

        // 创建 FIle
        File dir = new File("/Users/liliang/Downloads/index_db/file");
        int cursor = 1;
        // 迭代目录下的所有文件
        for (File file : dir.listFiles()) {
            //创建 Document
            Document doc = new Document();
            // 添加字段
            doc.add(new StringField("id", String.valueOf(cursor++), Field.Store.YES));
            doc.add(new TextField("name", file.getName(), Field.Store.YES));
            doc.add(new TextField("path", file.getAbsolutePath(), Field.Store.YES));
            doc.add(new TextField("content", new InputStreamReader(new FileInputStream(file), "gbk")));
            doc.add(new TextField("fileContent", readFile(file), Field.Store.YES));

            // 把文档添加到索引库
            indexWriter.addDocument(doc);
            // 提交
            indexWriter.commit();
        }
        // 关闭 IO流
        indexWriter.close();
    }

    /**
     * 读取文件 file 中的内容
     *
     * @param file
     * @return
     */
    private static String readFile(File file) throws Exception {
        StringBuilder str = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"gbk"));
        String line = null;
        while ((line = br.readLine()) != null) {
            str.append(line);
        }
        br.close();
        return str.toString();
    }
}
